import React, { useState, useEffect } from 'react';
import { Table, Input, Pagination, Modal } from 'antd';
import style from './index.module.css';

// 常见女性名字用字库
const femaleCharacters = ['芳', '婷', '娜', '敏', '静', '丽', '娟', '艳', '玲', '晶', '华', '倩', '琳', '颖', '薇', '雪', '蕾', '丹', '琪', '璇'];

// 获取称谓（先生/女士）
const getHonorific = (name) => {
  if (!name || name.length < 2) return '先生/女士';
  const givenName = name.slice(1);
  for (let char of givenName) {
    if (femaleCharacters.includes(char)) {
      return '女士';
    }
  }
  return '先生';
};

// 订单数据
const mockOrders = [
  {
    id: 'ORD20230615001',
    customer: { name: '李明', phone: '138****5678', avatar: 'https://picsum.photos/id/91/40/40' },
    service: { name: '推拿按摩（60分钟）', doctor: '王前台', room: '理疗室1' },
    amount: '268.00',
    paymentMethod: 'wechat',
    orderTime: '2023-06-15 09:30',
    checkoutTime: '2023-06-15 10:35',
    status: 'completed',
    remarks: '客户要求力道适中，重点按摩肩颈部位'
  },
  {
    id: 'ORD20230615002',
    customer: { name: '张华', phone: '139****8901', avatar: 'https://picsum.photos/id/92/40/40' },
    service: { name: '针灸治疗（60分钟）', doctor: '李前台', room: '治疗室2' },
    amount: '328.00',
    paymentMethod: 'member',
    orderTime: '2023-06-15 11:00',
    checkoutTime: '2023-06-15 12:05',
    status: 'processing',
    remarks: '需提前准备一次性针灸针'
  },
  {
    id: 'ORD20230615003',
    customer: { name: '赵丽', phone: '137****2345', avatar: 'https://picsum.photos/id/93/40/40' },
    service: { name: '艾灸调理（60分钟）', doctor: '陈前台', room: '艾灸室1' },
    amount: '298.00',
    paymentMethod: 'unpaid',
    orderTime: '2023-06-15 13:45',
    checkoutTime: '',
    status: 'pending',
    remarks: '预约下午3点，客户对艾草轻微过敏'
  },
  {
    id: 'ORD20230614025',
    customer: { name: '陈杰', phone: '136****6789', avatar: 'https://picsum.photos/id/94/40/40' },
    service: { name: '拔罐疗法（45分钟）', doctor: '王前台', room: '理疗室2' },
    amount: '198.00',
    paymentMethod: 'cash',
    orderTime: '2023-06-14 16:00',
    checkoutTime: '2023-06-14 16:50',
    status: 'completed',
    remarks: '无特殊要求'
  },
  {
    id: 'ORD20230614024',
    customer: { name: '林小红', phone: '135****3456', avatar: 'https://picsum.photos/id/95/40/40' },
    service: { name: '肩颈理疗套餐（90分钟）', doctor: '李前台', room: 'VIP室' },
    amount: '468.00',
    paymentMethod: 'alipay',
    orderTime: '2023-06-14 14:30',
    checkoutTime: '2023-06-14 16:05',
    status: 'cancelled',
    remarks: '客户临时有事取消，已告知可重新预约'
  }
];

// 获取支付方式图标
const getPaymentIcon = (method) => {
  switch (method) {
    case 'wechat': return <i className="fa fa-weixin text-green-500 mr-1.5"></i>;
    case 'alipay': return <i className="fa fa-alipay text-blue-500 mr-1.5"></i>;
    case 'cash': return <i className="fa fa-money text-green-600 mr-1.5"></i>;
    case 'member': return <i className="fa fa-credit-card text-blue-500 mr-1.5"></i>;
    default: return <i className="fa fa-credit-card text-gray-400 mr-1.5"></i>;
  }
};

// 获取支付方式文本
const getPaymentText = (method) => {
  const methodMap = {
    'wechat': '微信支付',
    'alipay': '支付宝',
    'cash': '现金支付',
    'member': '会员卡扣费',
    'unpaid': '未支付'
  };
  return methodMap[method] || '未知方式';
};

// 获取状态徽章
const getStatusBadge = (status) => {
  const statusMap = {
    'pending': { text: '待支付', class: style.statusPending },
    'cancelled': { text: '已取消', class: style.statusCancelled }
  };
  const result = statusMap[status] || { text: '', class: '' };
  return result.text ? <span className={`${style.statusBadge} ${result.class}`}>{result.text}</span> : null;
};

function Order() {
  // 状态管理
  const [orders, setOrders] = useState([]);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalOrders, setTotalOrders] = useState(0);
  const [paginatedOrders, setPaginatedOrders] = useState([]);

  // 初始化订单数据并设置分页
  useEffect(() => {
    setOrders(mockOrders);
    setTotalOrders(mockOrders.length);
    handlePagination(mockOrders, currentPage, pageSize);
  }, []);

  // 当页码或每页条数变化时重新计算分页
  useEffect(() => {
    handlePagination(orders, currentPage, pageSize);
  }, [currentPage, pageSize, orders]);

  // 处理分页逻辑
  const handlePagination = (data, page, size) => {
    const startIndex = (page - 1) * size;
    const endIndex = startIndex + size;
    setPaginatedOrders(data.slice(startIndex, endIndex));
  };

  // 处理页码变化
  const handlePageChange = (page, size) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 处理行点击事件，打开详情弹窗
  const handleRowClick = (record) => {
    setCurrentOrder(record);
    setDetailVisible(true);
  };

  // 关闭详情弹窗
  const handleCloseDetail = () => {
    setDetailVisible(false);
    setCurrentOrder(null);
  };

  return (
    <div className={style.order}>
      <div className={style.orderContainer}>
        {/* 页面标题与搜索区域 */}
        <section className={style.pageHeader}>
          <div className={style.headerContent}>
            <div>
              <h2 className={style.pageTitle}>订单管理</h2>
              <p className={style.pageDescription}>
                <i className="fa fa-calendar-check-o mr-1.5 text-secondary"></i>
                管理所有理疗服务订单，支持查询、筛选与状态修改
              </p>
            </div>
            <div className={style.listHeader}>
              <div className={style.listCount}>
                <div className={style.filterContainer}>
                  <div className={style.searchGroup}>
                    {/* 搜索框 */}
                    <div className={style.searchInput}>
                      <Input
                        type="text"
                        placeholder="搜索订单号/客户姓名"
                        className={style.formInput}
                      />
                      <div className={style.searchIcon}>
                        <i className="fa fa-search"></i>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* 订单列表 */}
        <section className={style.orderListSection}>
          <div className={style.tableContainer}>
            <Table
              dataSource={paginatedOrders}
              rowKey="id"
              pagination={false}
              className={style.orderTable}
              onRow={(record) => ({
                onClick: () => handleRowClick(record),
                style: {
                  cursor: 'pointer',
                  height: '80px'
                }
              })}
              scroll={{ x: 'max-content' }}
            >
              <Table.Column
                title="订单ID"
                dataIndex="id"
                key="id"
                width={140}
              />
              <Table.Column
                title="姓名"
                key="customerName"
                width={120}
                render={(record) => (
                  <div className={style.customerName}>
                    <div className={style.userIcon}>
                      <i className="fa fa-user-circle-o"></i>
                    </div>
                    <span>
                      {record.customer.name.slice(0, 1)}{getHonorific(record.customer.name)}
                    </span>
                  </div>
                )}
              />
              <Table.Column
                title="项目名字"
                key="service"
                width={200}
                render={(record) => (
                  <div className={style.serviceName}>{record.service.name}</div>
                )}
              />
              <Table.Column
                title="价格"
                key="amount"
                width={100}
                render={(record) => <span className={style.orderAmount}>¥{record.amount}</span>}
              />
              <Table.Column
                title="支付方式"
                key="paymentMethod"
                width={140}
                render={(record) => (
                  <span className={style.paymentMethod}>
                    {getPaymentIcon(record.paymentMethod)}
                    {getPaymentText(record.paymentMethod)}
                  </span>
                )}
              />
              <Table.Column
                title="日期"
                key="orderTime"
                width={120}
                render={(record) => record.orderTime.split(' ')[0]}
              />
            </Table>
          </div>

          {/* 分页组件 */}
          <div className={style.pagination}>
            <div className={style.paginationInfo}>
              显示 {Math.min((currentPage - 1) * pageSize + 1, totalOrders)} 到 {Math.min(currentPage * pageSize, totalOrders)} 条，共 {totalOrders} 条记录
            </div>
            <div className={style.paginationButtons}>
              <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={totalOrders}
                pageSizeOptions={['10', '20', '50']}
                showSizeChanger
                showQuickJumper
                showTotal={(total) => `共 ${total} 条`}
                onChange={handlePageChange}
                onShowSizeChange={handlePageChange}
              />
            </div>
          </div>
        </section>
      </div>

      {/* 订单详情弹窗 - 重新排版，居中显示，无滚动条 */}
      <Modal
        title="订单详情"
        open={detailVisible}
        onCancel={handleCloseDetail}
        footer={[
          <button 
            key="close" 
            className={`${style.modalBtn} ${style.cancelBtn}`} 
            onClick={handleCloseDetail}
          >
            关闭
          </button>
        ]}
        maskClosable={false}
        centered={true}  // 确保弹窗在页面中心
        bodyStyle={{ padding: 0 }}
        width={600}
      >
        {currentOrder && (
          <div className={style.detailContent}>
            {/* 订单基本信息 - 顶部区域 */}
            <div className={style.detailHeader}>
              <div className={style.orderIdSection}>
                <div className={style.detailLabel}>订单编号</div>
                <div className={style.detailValue}>{currentOrder.id}</div>
              </div>
              
              <div className={style.customerInfoSection}>
                <div className={style.detailLabel}>客户信息</div>
                <div className={style.detailValue}>
                  {currentOrder.customer.name.slice(0, 1)}{getHonorific(currentOrder.customer.name)}
                  <span className={style.customerPhone}>（{currentOrder.customer.phone}）</span>
                </div>
              </div>
            </div>
            
            {/* 时间信息 - 紧凑布局 */}
            <div className={style.detailTimeSection}>
              <div className={style.timeItem}>
                <div className={style.detailLabel}>下单时间</div>
                <div className={style.detailValue}>{currentOrder.orderTime}</div>
              </div>
              
              {currentOrder.checkoutTime && (
                <div className={style.timeItem}>
                  <div className={style.detailLabel}>结账时间</div>
                  <div className={style.detailValue}>{currentOrder.checkoutTime}</div>
                </div>
              )}
            </div>
            
            {/* 服务与支付信息 - 双列网格布局 */}
            <div className={style.detailServicePaymentSection}>
              <div className={style.serviceItem}>
                <div className={style.detailLabel}>服务项目</div>
                <div className={style.detailValue}>{currentOrder.service.name}</div>
              </div>
              
              <div className={style.serviceItem}>
                <div className={style.detailLabel}>服务人员</div>
                <div className={style.detailValue}>{currentOrder.service.doctor}</div>
              </div>
              
              <div className={style.serviceItem}>
                <div className={style.detailLabel}>服务房间</div>
                <div className={style.detailValue}>{currentOrder.service.room}</div>
              </div>
              
              {/* 支付方式 */}
              {currentOrder.paymentMethod !== 'unpaid' && (
                <div className={style.paymentItem}>
                  <div className={style.detailLabel}>支付方式</div>
                  <div className={style.detailValue}>
                    <span className={style.paymentMethod}>
                      {getPaymentIcon(currentOrder.paymentMethod)}
                      {getPaymentText(currentOrder.paymentMethod)}
                    </span>
                  </div>
                </div>
              )}
              
              {/* 订单状态 */}
              {(currentOrder.status === 'pending' || currentOrder.status === 'cancelled') && (
                <div className={style.statusItem}>
                  <div className={style.detailLabel}>订单状态</div>
                  <div className={style.detailValue}>
                    {getStatusBadge(currentOrder.status)}
                  </div>
                </div>
              )}
              
              {/* 订单金额 */}
              <div className={style.amountItem}>
                <div className={style.detailLabel}>订单金额</div>
                <div className={`${style.detailValue} ${style.totalAmount}`}>
                  ¥{currentOrder.amount}
                </div>
              </div>
            </div>
            
            {/* 备注信息 - 自适应高度 */}
            <div className={style.detailRemarksSection}>
              <div className={style.detailLabel}>备注信息</div>
              <div className={`${style.detailValue} ${style.remarksBox}`}>
                {currentOrder.remarks || <span className={style.emptyRemarks}>无特殊备注</span>}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

export default Order;
